﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebPortal.Models.EntityModels;
using WebPortal.Models.ViewModel;

namespace WebPortal.Controllers
{
    public class CategoriesController : BaseController
    {
        //
        // GET: /Categories/

        public ActionResult Index()
        {
            var categories = (from cat in dbCategories.Categories select cat).ToList();
            return View(categories);
        }

        public ActionResult Edit(CategoryModel cat)
        {
            if (ModelState.IsValid)
            {
                if (cat.Delete != null)
                {
                    // delete mode                    
                    var categories = (from catg in dbCategories.Categories where catg.CategoryID == cat.Id select catg).ToList();
                    Categories category = categories[0];
                    dbCategories.DeleteObject(category);
                }
                else
                {
                    if (cat.Id == 0)
                    {
                        // new mode
                        Categories category = new Categories();
                        category.Name = cat.Name;
                        dbCategories.AddToCategories(category);
                    }
                    else
                    {
                        // edit mode
                        var categories = (from catg in dbCategories.Categories where catg.CategoryID == cat.Id select catg).ToList();
                        Categories category = categories[0];
                        category.Name = cat.Name;
                    }
                }
                try
                {
                    dbCategories.SaveChanges();
                }
                catch (System.Data.UpdateException e)
                {
                    //Can not insert to database
                }
            }
            return this.RedirectToAction("Index");
        }

    }
}
